import { cmdExec } from './tool';
import { DeviceService } from '../device/device.service';
import { AppListService } from '../app-list/app-list.service';

const deviceList = new Set<string>();

export const watch = async () => {
  const list = await cmdExec('hdc list targets').then((res) =>
    res
      .split(/\r?\n/)
      .filter((item: string) => item && !item.includes('Empty')),
  );
  for (const SN of list) {
    if (deviceList.has(SN)) continue;
    console.log('新设备上线', SN);
    initDevice(SN);
    deviceList.add(SN);
  }
  const tmp = [...deviceList];
  for (const SN of tmp) {
    if (list.includes(SN)) continue;
    console.log('设备下线', SN);
    clearDevice(SN);
    deviceList.delete(SN);
  }
};

const clearDevice = (SN: string) => {
  const deviceService = new DeviceService();
  deviceService.clearDeviceInfo(SN);
  const appListService = new AppListService();
  appListService.clearAppList(SN);
};

const initDevice = (SN: string) => {
  const deviceService = new DeviceService();
  deviceService.getDeviceInfo(SN, false);
  const appListService = new AppListService();
  appListService.getAppList(SN);
};
